//
//  CreateJobSearchInstallerView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/7.
//

import UIKit
import SwiftyJSON
import HandyJSON
enum SearchInstallerType: Int{
    case installer = 0
    case designer
    case electrician
}
class CreateJobSearchInstallerView: UIView {
    private var type: SearchInstallerType = .installer
    private var defaultSearchValue: String = ""
    var selectClosure: ((MyInformationModel)->Void)?
    let tableView = TableView()
    var list = [MyInformationModel]()
    let titleLabel = ContentLabel(R.font.interSemiBold(size: 17))
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(_ type: SearchInstallerType,title: String, defaultSearchValue: String ) {
        super.init(frame: CGRect.zero)
        self.type = type
        self.defaultSearchValue = defaultSearchValue
        self.titleLabel.text = title
        setUpView()
    }
    private func setUpView() {
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        let backView = UIView()
        backView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(40)
            make.left.right.bottom.equalToSuperview()
        }
        //modelSelectLabel
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(30)
            make.centerX.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //Done btn
        let closeBtn = UIButton()
        closeBtn.setImage(R.image.me_presentvc_close(), for: UIControl.State.normal)
        backView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.right.equalTo(-8)
            make.width.height.equalTo(40)
            make.centerY.equalTo(titleLabel)
        }
        let searchBackView = UIView()
        searchBackView.backgroundColor = UIColor(hexStr: "#F5F5F5")
        backView.addSubview(searchBackView)
        searchBackView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(15)
            make.height.greaterThanOrEqualTo(0)
            make.left.right.equalToSuperview()
        }
        
        let searchTextfield = DIYTextField()
        searchTextfield.placeholder = R.string.localizable.search()
        searchTextfield.showLeftImageView("edit_address_search_icon")
        searchBackView.addSubview(searchTextfield)
        searchTextfield.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(40)
            make.bottom.equalTo(-12)
        }
        //
        backView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchBackView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        //
        searchTextfield.delegate = self
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SearchModellCell.self, forCellReuseIdentifier: SearchModellCell.reuseCellIdentifier)
        //
        closeBtn.addTarget(self, action: #selector(closeBtnClick), for: UIControl.Event.touchUpInside)
        
        searchTextfield.addTarget(self, action: #selector(textFieldEditChanged(_:)), for: UIControl.Event.editingChanged)
        searchTextfield.delegate = self
        if self.defaultSearchValue != ""{
            searchTextfield.text = self.defaultSearchValue
        }
        
        tableView.loadFaildView.retryBtn.addTarget(self, action: #selector(retryBtnClick), for: UIControl.Event.touchUpInside)
        self.loadData()
    }
    
    @objc private func retryBtnClick(){
        self.loadData()
    }
    @objc func textFieldEditChanged(_ textField: UITextField){
        self.defaultSearchValue = textField.text ?? ""
        self.loadData()
    }
    @objc func closeBtnClick(){
        self.removeFromSuperview()
    }
    func loadData(){
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            if let list = result as? [MyInformationModel]{
                var realList = list
                if strongSelf.defaultSearchValue.count > 0{//如果有过滤条件，自己过滤
                    realList = list.filter({$0.name.contains(strongSelf.defaultSearchValue)})
                }
                strongSelf.list = realList
                strongSelf.tableView.reloadData()
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.tableView.showResultView(nodataFlag:strongSelf.list.count == 0 ? true: false)
        } errorBlock: { [weak self] (code, error) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            strongSelf.list.removeAll()
            strongSelf.tableView.reloadData()
            strongSelf.tableView.showRetryView()
            Tool().showAlertViewWithOneBtn(message: error)
        }
        ModelViewUtil.shared.showLoadingView(parentView: self)
        if type == .installer {
            vm.getInstallerList(companyId: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id)
        }else if type == .designer{
            vm.getDesignerList(companyId: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id)
        }else if type == .electrician{
            vm.getElectricianList(companyId: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id)
        }
    }
}
extension CreateJobSearchInstallerView: UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: SearchInstallerCell.reuseCellIdentifier) as? SearchInstallerCell
        if cell == nil {
            cell = SearchInstallerCell(style: .default, reuseIdentifier: SearchInstallerCell.reuseCellIdentifier)
        }
        cell!.setData(self.list[indexPath.row])
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectClosure?(self.list[indexPath.row])
        self.removeFromSuperview()
    }
}
